/**
 * authentication.async.test.js
 * 鉴权中异步action的单元测试用例
 *
 * created by qiuwei
 * version 1.0.0
 * 2016年03月12日
 */

import { expect } from 'chai';
import { applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

const middlewares = [ thunk ];

/**
 * 使用中间件模拟 Redux store。
 */
export default function mockStore(getState, expectedActions, done) {
	if (!Array.isArray(expectedActions)) {
		throw new Error('expectedActions should be an array of expected actions.')
	}
	if (typeof done !== 'undefined' && typeof done !== 'function') {
		throw new Error('done should either be undefined or function.')
	}

	function mockStoreWithoutMiddleware() {
		return {
			getState() {
				return typeof getState === 'function' ?
					getState() :
					getState
			},

			dispatch(action) {
				const expectedAction = expectedActions.shift();

				try {
					expect(action).to.deep.equal(expectedAction);
					if (done && !expectedActions.length) {
						done();
					}
					return action
				} catch (e) {
					done(e);
				}
			}
		}
	}

	const mockStoreWithMiddleware = applyMiddleware(
		...middlewares
	)(mockStoreWithoutMiddleware)

	return mockStoreWithMiddleware()
}